package cn.meng.base.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro配置类
 * @author 万梦辉
 */

@Configuration
public class ShiroConfig {

    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    @Bean("securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //关联Realm
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        filterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //开启认证登录页 （请求改为对应的请求，告诉前端进行路由跳转到登录页） Shiro对于没权限的请求会处理跳转到这里设置的请求。
        filterFactoryBean.setLoginUrl("/toLogin");

        //设置无权限的请求  跳转到对应返回错误信息的请求，告诉前端无权限，抛出弹框等提示
        filterFactoryBean.setUnauthorizedUrl("/golbal/sendNoPermissionMessage");

        //采用Shiro注销，设置跳转到登录页面
        LogoutFilter logoutFilter = new LogoutFilter();
        //logoutFilter.setRedirectUrl("/toLogin");

        //添加Shiro内置的过滤器
        /**
         * anon：无需认证就可以访问
         * authc：必须认证了才能访问
         * user：必须拥有  【记住我】 功能才能用
         * perms：拥有某个资源的权限才可以访问
         * role：拥有某个角色菜可以访问
         */
        Map<String,String> filterMap = new LinkedHashMap<String, String>();

        //权限控制,必须拥有对应的权限才可以访问资源(静态访问控制)
        filterMap.put("/login","anon");
        filterMap.put("/test/add","perms[add]");
        filterMap.put("/test/update","perms[update]");
        filterMap.put("/test/delete","perms[delete]");

        filterFactoryBean.setFilterChainDefinitionMap(filterMap);

        //拦截注销请求，进行注销处理
        Map<String, Filter> filterLogout = new LinkedHashMap<String, Filter>();
        filterLogout.put("/admin/loginOut",logoutFilter);
        filterFactoryBean.setFilters(filterLogout);

        return filterFactoryBean;
    }

}
